/**
 * 编辑作者：张诗涛
 * 创建时间：2018年5月8日 16点12分
 * 功能分类：权限验证数据操作API
 */
import * as  fs from 'fs';
import * as  path from 'path';
import { UserInfoEntity } from '../entitys/entity';

class ClientStore {
    private readonly path: string;
    private dataList: { token: string, expiration: number, data: UserInfoEntity }[] = [];

    constructor(relativePath: string) {
        this.path = path.join(__dirname, relativePath);

        this.readAsync();
    }
    hasValid(token: string): boolean {
        if (!token) return false;

        this.readAsync();

        let ret = false, item;
        if (this.dataList.some(function (v) {
            if (v.token === token) {
                item = v;
            }
            return v.token === token;
        })) {

            let num = new Date().getTime();

            if (item.expiration < num) {
                ret = true;
            }
        }
        if (!ret) {
            this.remove(token);
        }

        this.writeAsync();

        return ret;
    }
    remove(token: string) {
        this.readAsync();

        for (let i = 0; i < this.dataList.length; i++) {
            if (this.dataList[i].token === token) {
                this.dataList.splice(i, 1);
                break;
            }
        }

        this.writeAsync();
    }
    add(token: string, expiration: number, user: UserInfoEntity) {
        this.readAsync();

        this.dataList.push({ token: token, expiration: expiration, data: user });

        this.writeAsync();
    }
    private readAsync() {
        if (fs.existsSync(this.path)) {
            this.dataList = JSON.parse(fs.readFileSync(this.path).toString()) || [];
        }
    }
    private writeAsync() {
        fs.writeFileSync(this.path, JSON.stringify(this.dataList));
    }
}

export { ClientStore }